package com.cloudlinkscm.loms.services.base.notify.service;

import com.cloudlinkscm.loms.services.base.notify.assemblers.EmailMessageModelAssembler;
import com.cloudlinkscm.loms.services.base.notify.constant.SendStatusEnum;
import com.cloudlinkscm.loms.services.base.notify.domain.email.EmailMessageManager;
import com.cloudlinkscm.loms.services.base.notify.dto.email.EmailMessageDto;
import com.cloudlinkscm.loms.services.base.notify.dto.SendResultDto;
import com.cloudlinkscm.loms.services.base.notify.model.entity.EmailMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 通知服务
 *
 * @author : tac
 * @date : 2017/6/14
 */
@Component
public class NotificationService {
    private EmailMessageManager emailMessageManager;

    @Autowired
    private EmailMessageModelAssembler emailMessageModelAssembler;

    @Autowired
    public NotificationService(EmailMessageManager emailMessageManager) {
        this.emailMessageManager = emailMessageManager;
    }

    /**
     * 发送email（如果是非实时发送，则先存到数据库中）
     */
    public SendResultDto sendEmail(EmailMessageDto emailMessageDto){
        return sendEmail(emailMessageModelAssembler.toBo(emailMessageDto));
    }

    private SendResultDto sendEmail(EmailMessage message){
        SendResultDto result;

        emailMessageManager.newMessage(message);

        if(emailMessageManager.isSendNow(message)){
            result = emailMessageManager.send(message);
            emailMessageManager.setStatus(message.getId(), result.getState());
            return result;
        }else{
            result = new SendResultDto();
            result.setMsg("操作成功，已将邮件添加至待发送列表");
            result.setState(SendStatusEnum.NOT_SEND.val);
            return result;
        }
    }
}
